from django.shortcuts import render_to_response
from compmanage.Computer_lab.models import * # import all models from
from django.contrib.auth import authenticate, login
from django.http import HttpResponseRedirect, HttpResponse  # use with POST method import
from django.views.decorators.csrf import *
from django.contrib import auth

def home_page(request):
	if request.user.is_authenticated():
		return render_to_response('login_success.html')
	else:
		return render_to_response('home.html')  # link to home page
	
def success_login(request):
	return render_to_response('login_success.html')  # link to home page

def success(request):
    if not request.user.is_authenticated():
    	messages = 'You are not login, '
    	return render_to_response('home.html', {'messages': messages})
    else:
		return render_to_response('success.html')  # link to success page

def submit_page(request):
    if not request.user.is_authenticated():
    	messages = 'You are not login, '
    	return render_to_response('home.html', {'messages': messages})
    else:
		return render_to_response('form.html')  # link to submit page

def logout_page(request):
    return render_to_response('logout.html')

def report_page(request):
    if not request.user.is_authenticated():
    	messages = 'You are not login, '
    	return render_to_response('home.html', {'messages': messages})
    else:
		data = Repair.objects.filter()
		count = [Repair.objects.filter(status='Repair').count(), Repair.objects.all().count()-Repair.objects.filter(status='Repair').count()]
		return render_to_response('report.html', {'datas' : data, 'counts' : count})

def fix_table(request):
    if not request.user.is_authenticated():
    	messages = 'You are not login, '
    	return render_to_response('home.html', {'messages': messages})
    else:
		to_fix = Repair.objects.filter(status__contains = "Don't repair")  # select computer that don't fixed yet from all computers
		return render_to_response('fix_table.html', locals())  # show table of error computer 

def fix_detail(request, name):  # get parametr named name that keep computer name to function
    if not request.user.is_authenticated():
    	messages = 'You are not login, '
    	return render_to_response('home.html', {'messages': messages})
    else:
		com_fix = Repair.objects.get(Com_model=name)
		tech = Technician.objects.filter()
		return render_to_response('fix_detail.html', locals())

def fix_detail_submit(request):
    errors = []  # empty list of error
    com_fix = Repair.objects.get(Com_model=request.GET['name'])
    tech =Technician.objects.all()
 
    if 'fixdate' in request.GET and request.GET['fixdate']:
        fixdate = request.GET['fixdate']
        if request.GET['fixdate'] == "Enter Date":  # don't fill date yet
	    errors.append('Please enter date of fix.')  # show error message
	if not request.GET['fixdate']:  # don't fill date yet
	    errors.append('Please enter date of fix')  # show error message
	if not errors:  # create object update
            tech_up = Repair.objects.get(Com_model = request.GET['name'])
	    tech_up.status = "Repair"
            tech_up.tech = request.GET['Technician']
	    tech_up.fix_date = request.GET['fixdate']   
	    tech_up.save()
	    return HttpResponseRedirect('report.html')  # return 
    return render_to_response('fix_detail.html', locals())  # return fix detail form to fill all blank

def submit(request):
    # Store error for null submit
    errors = []
    if request.method == 'GET':
        if not request.GET['com_model']:
            errors.append('Enter computer model.')
        if not request.GET['a']:
            errors.append('Enter repair data.')
        if not errors:
            #History Objects
            if not History.objects.filter(com_model=request.GET['com_model']):
                history = History.objects.create(com_model=request.GET['com_model'], Submit_time = 1)
            else:
                h = History.objects.get(com_model=request.GET['com_model'])
                h.Submit_time = int(h.Submit_time)+1
                h.save()
            #Create repair data object
            if not Repair.objects.filter(Com_model=request.GET['com_model']):
                repair = Repair.objects.create(Com_model=request.GET['com_model'], Repair=request.GET['a'], status="Don't repair", tech='-')
            else:
                com = request.GET['com_model']
                html = "<html><body><pre>Computer name '%s' has been in database!. <a href='http://127.0.0.1:8000/add/'>Back</a></pre></body></html>" % com
                return HttpResponse(html)
            return HttpResponseRedirect('success')
	return render_to_response('form.html', {'errors': errors})

class X_axis:  # declare class for keep object of x axis
	def __init__(self, com_ip, x_start, submit_time, xpos):
		self.com_ip = com_ip  # name of computer under x axis
		self.x_start = x_start  # next x scale
		self.submit_time = submit_time  # frequency of submit for each computer
		self.xpos = xpos

class Y_axis:  # declare class for keep object of y axis
	def __init__(self, y_start, count, line):
		self.count = count  # number of scale
		self.y_start = y_start  # position of y scale 
	 	self.line = line  # position of line scale

def draw_graph(request):
	x_start = 90
	y_start = 460
	line = 417.5
	xpos = 85
	list_x = []  # empty list of object x axis
	list_y = []  # empty list of object y axis
	
	hist = History.objects.all()
	com_ip = History.objects.filter().count()  # count computer in history
	temp_freq = History.objects.values_list("Submit_time", flat=True)
	freq = list(temp_freq)  # convert to list type
	max_y = max(freq)  # find max number of Submit time in history
	find_y = (max_y/10)+1  # find frequency of number scale
	
	for x in range(0, com_ip): 
	    temp_com = History.objects.values_list("com_model", flat=True)  # list of com_model
	    l = list(temp_com)
	    com_model = str(l[x])
	    height = 460.0-(430.0/(find_y*10.0))*freq[x]  # find height of graph
	    obj_x = X_axis(com_model, x_start, height, xpos)  # create object of class X_axis
	    x_start = x_start+45
	    xpos = xpos +44
	    list_x.append(obj_x)  # append to list

	# loop for keep number and line at scale
	for y in range(0, 11):  # scale y axis = 10 part
	    count = find_y*y  # number scale y axis
            obj_y = Y_axis(y_start, count, line)  # create object of class X_axis
	    list_y.append(obj_y)  # append to list
	    y = y-1
	    y_start = y_start-42
	    line = line - 42.5
	    
	if not request.user.is_authenticated():
		return render_to_response('home.html')
	else:
		return render_to_response('graph.html', locals())  # show history graph

@csrf_exempt
def login(request):
    errors = []
    if request.method == 'POST':
		user = authenticate(username=request.POST['username'], password=request.POST['password'])
		if not request.POST['username']:
			errors.append('Enter username.')
		if not request.POST['password']:
			errors.append('Enter password.')
		if not errors:
			if user is not None:
				if user.is_active:
					auth.login(request, user)
					# success
					return HttpResponseRedirect('/success_login')
		# Show an error message
		return render_to_response('home.html', {'errors': errors})

@csrf_exempt
def logout(request):
	messages = 'You are now log out, '
	auth.logout(request)
    # Redirect to a success page.
        return render_to_response('home.html', {'messages': messages})

